//
//  NetWorkTools.swift
//  WeiBo test
//
//  Created by Aquarius_wing on 16/5/12.
//  Copyright © 2016年 Wing. All rights reserved.
//

import UIKit
import AFNetworking
private let  weiboDomain = "com.baidu.data.error"

//线上
private let hostname = "https://api.weibo.com/"
enum HTTPMethod:String {
    case POST = "POST"
    case GET = "GET"
}

class NetWorkTools: AFHTTPSessionManager {
    
    //定义单例对象
    static let sharedTools:NetWorkTools = {
        let url = NSURL(string: hostname)
        let tools = NetWorkTools(baseURL: url)
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
    }()
    
    func requestJsonDict(method:HTTPMethod,urlString:String,parameters:[String:AnyObject]?,finished:(result:[String : AnyObject]?, error:NSError?)->()){
        
        //如果是GET
        if method == HTTPMethod.GET {
            GET(urlString, parameters: parameters, success: { (_, result) in
                //判断数据结果是否是字典
                if let dict = result as? [String:AnyObject]{
                    //执行成功回调
                    finished(result: dict, error: nil)
                }
                //此时数据格式不匹配
                //自定义错误信息
                //一般自定义errorCode 为负值
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                }, failure: { (_, error) in
                    //执行错误回调
                    finished(result: nil, error: error)
                    print("GET出错",error)
            })
        }else{
            //POST
            POST(urlString, parameters: parameters, success: { (_, result) in
                //判断数据结果是否是字典
                if let dict = result as? [String:AnyObject]{
                    //执行成功回调
                    finished(result: dict, error: nil)
                }
                
                //此时数据格式不匹配
                //自定义错误信息
                //一般自定义errorCode 为负值
                let dataError = NSError(domain: weiboDomain, code: -10000, userInfo: [NSLocalizedDescriptionKey:"数据错误"])
                
                }, failure: { (_, error) in
                    //执行错误回调
                    finished(result: nil, error: error)
                    print("POST出错",error)
            })
        }
    }
}
